
package com.yesep.learn.mqtt.client.handler.protocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yesep.learn.mqtt.client.common.event.EventType;
import com.yesep.learn.mqtt.client.common.util.ChannelUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.codec.mqtt.MqttSubAckMessage;

/**
   * 消息编号：9
 * @Description: SUBACK连接处理，订阅应答
 */
public class SubAck {

	private static final Logger logger = LoggerFactory.getLogger(SubAck.class);

	public void process(ChannelHandlerContext ctx, MqttSubAckMessage message) {
		boolean success = true;
		if (message.payload().grantedQoSLevels().isEmpty())
			success = false;
		if (success) {
			for (int qos : message.payload().grantedQoSLevels()) {
				if (MqttQoS.FAILURE.equals(MqttQoS.valueOf(qos))) {
					success = false;
					break;
				}
			}
		}
		if (success) {
			ChannelUtil.triggerUserEvent(ctx, EventType.SUBSCRIBE_SUCCESS, message);
			logger.info("subscribe success : {} ", ChannelUtil.clientId(ctx.channel()));
		} else {
			ChannelUtil.triggerUserEvent(ctx, EventType.SUBSCRIBE_FAILURE, message);
			logger.info("subscribe failure : {} ", ChannelUtil.clientId(ctx.channel()));
		}
	}

}
